package com.example.ruomi.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ruomi.entity.Users;
import com.example.ruomi.pojo.enums.RoleEnum;
import com.example.ruomi.pojo.enums.StatusEnum;
import com.example.ruomi.service.UsersService;
import com.example.ruomi.utils.result.Result;
import com.example.ruomi.utils.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.ruomi.utils.RedisUtil;

import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/list")
    public Result getUsers() {
        List<Users> users = usersService.list();
        return new Result<>(200, "success", users);
    }

    @PostMapping("/register")
    public Result userRegisterController(@RequestParam("username") String username,
                                         @RequestParam("code") String code) {
        if (!redisUtil.hasKey(username)) {
            return ResultUtil.error(400, "验证码不存在或已过期");
        }
        long expireTimeInSeconds = redisUtil.getExpire(username);
        if (expireTimeInSeconds <= 0) {
            return ResultUtil.error(400, "验证码已过期");
        }
        // 获取验证码并继续处理
        String verificationCode = redisUtil.get(username).toString();
        if (code.isEmpty() || !code.equals(verificationCode)) {
            return ResultUtil.error(400, "验证码错误");
        }
        // 查询用户是否存在,不需要返回查询结果
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", username);
        boolean selectUser = usersService.getOne(queryWrapper) != null;
        if (selectUser) {
            return ResultUtil.error(400, "用户已存在");
        }
        // 注册用户
        try {
            Users user = new Users();
            user.setUsername(IdUtil.simpleUUID().substring(0, 12));
            user.setPhoneNumber(username);
            user.setRoleId(RoleEnum.USER.getValue());
            user.setStatus(StatusEnum.NORMAL.getValue());
            usersService.save(user);
            user = usersService.getOne(queryWrapper);
            // 注册成功后删除验证码
            redisUtil.del(username);
            return ResultUtil.success(user);
        } catch (Exception e) {
            redisUtil.del(username);
            return ResultUtil.error(500, "注册失败");
        }
    }

    @GetMapping("/random-code")
    public Result getRandomCode(@RequestParam("phone") String phone) {
        // 校验phone是否合法
        if (phone.length() != 11) {
            return ResultUtil.error(400, "手机号码格式错误");
        }
        // 查询验证码是否存在,存在则清空验证码
        if (redisUtil.hasKey(phone)) {
            redisUtil.del(phone);
        }
        // 生成随机验证码,6位数字
        String code = RandomUtil.randomNumbers(6);
        // 保存验证码到redis
        redisUtil.set(phone, code, 60 * 5);
        // 发送验证码到手机
        return ResultUtil.success(code);
    }



    @PostMapping("/login")
    public Result userLoginController(@RequestParam("username") String username,
                                      @RequestParam("password") String password) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", username);
        Users user = usersService.getOne(queryWrapper);
        if (user == null) {
            return ResultUtil.error(404, "用户不存在");
        }
        String passwordHash = SecureUtil.sha256(password);
        if (!user.getPasswordHash().equals(passwordHash)) {
            return ResultUtil.error(401, "密码错误");
        }
        return ResultUtil.success(user);
    }
}
